package com.java.cart.interceptor;

import com.java.auth.entity.UserInfo;
import com.java.auth.utils.JwtUtils;
import com.java.cart.config.JwtProperties;
import com.java.common.utils.CookieUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author jl
 * @description
 * @date 2019-11-07 14:45
 * 1.定义login拦截器
 * 2.注册自定义拦截器
 */
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private JwtProperties jwtProperties;

    private static final ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = CookieUtils.getCookieValue(request, jwtProperties.getCookieName());
        //解析token,获取用户信息
        UserInfo userInfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
        if (userInfo == null) {
            return false;
        }
        //用户信息存放到线程局部变量ThreadLocal,可以在Controller、Service中取出
        THREAD_LOCAL.set(userInfo);
        return true;
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空线程局部变量.因为使用的是tomcat的线程池,线程不会结束,也就不会自动释放局部变量.
        THREAD_LOCAL.remove();
    }

    public static UserInfo getUserInfo() {
        return THREAD_LOCAL.get();
    }

}
